package repository

import (
	"github.com/lab-online/internal/report/entity"
	"github.com/lab-online/internal/report/infra/model"
	"gorm.io/gorm"
)

func (r *Repository) SaveReport(
	reportEntity entity.ReportEntity,
) (entity.ReportEntity, error) {
	report := model.New(model.WithEntity(reportEntity))

	var err error
	if report.ID == 0 {
		err = r.db.Create(report).Error
	} else {
		err = r.db.
			Session(&gorm.Session{FullSaveAssociations: true}).
			Updates(report).Error
	}

	if err != nil {
		return nil, r.errorHandler(err)
	}

	return report.ToEntity(), nil
}
